1. Работа с Vue.js - Компоненты, Props
Введение
Vue.js — это современный фреймворк для построения интерфейсов. Его главный принцип — компонентный подход: сайт делится на блоки (компоненты), каждый отвечает за свою часть интерфейса.
Компоненты пишутся в файлах с расширением .vue
, которые обычно содержат:
<template>
— шаблон (разметка).<script>
— логика (JavaScript).<style>
— оформление (CSS).
Документация:
Отличный конспект 👍
Давайте перепишем все задания с использованием <script setup>
, чтобы код стал современным и компактным.
Практическая часть с <script setup>
Задание 1. Создание компонента
src/components/HelloWorld.vue
:
<template>
<div>
<h2>Привет из компонента!</h2>
<p>{{ message }}</p>
</div>
</template>
<script setup>
import { ref } from 'vue'
const message = ref("Это сообщение внутри компонента")
</script>
Задание 2. Использование компонента в App.vue
<template>
<HelloWorld />
</template>
<script setup>
import HelloWorld from './components/HelloWorld.vue'
</script>
Задание 3. Передача данных (props)
<!-- App.vue -->
<template>
<HelloWorld text="Сообщение из App.vue" />
</template>
<script setup>
import HelloWorld from './components/HelloWorld.vue'
</script>
<!-- HelloWorld.vue -->
<template>
<div>
<h2>{{ text }}</h2>
<p>{{ message }}</p>
</div>
</template>
<script setup>
import { ref } from 'vue'
const props = defineProps({
text: String
})
const message = ref("Сообщение изнутри")
</script>
Задание 4. Передача данных обратно (события)
<!-- HelloWorld.vue -->
<template>
<button @click="emit('send', message)">Отправить</button>
</template>
<script setup>
import { ref } from 'vue'
const message = ref("Сообщение для родителя")
const emit = defineEmits(['send'])
</script>
<!-- App.vue -->
<template>
<HelloWorld text="Пример" @send="getMessage"/>
<p>Получено: {{ received }}</p>
</template>
<script setup>
import { ref } from 'vue'
import HelloWorld from './components/HelloWorld.vue'
const received = ref("")
function getMessage(msg) {
received.value = msg
}
</script>
Задание 5. Pinia (хранилище данных)
src/stores/counter.js
:
import { defineStore } from 'pinia'
export const useCounterStore = defineStore('counter', {
state: () => ({ count: 0 }),
actions: {
increment() {
this.count++
}
}
})
App.vue
:
<script setup>
import { useCounterStore } from './stores/counter'
const counter = useCounterStore()
</script>
<template>
<p>Счётчик: {{ counter.count }}</p>
<button @click="counter.increment">Увеличить</button>
</template>
Задание 6. Vue Router (переходы между страницами)
src/views/Home.vue
:
<template><h1>Главная</h1></template>
src/views/About.vue
:
<template><h1>О проекте</h1></template>
src/router/index.js
:
import { createRouter, createWebHistory } from 'vue-router'
import Home from '../views/Home.vue'
import About from '../views/About.vue'
const routes = [
{ path: '/', component: Home },
{ path: '/about', component: About }
]
const router = createRouter({
history: createWebHistory(),
routes
})
export default router
App.vue
:
<template>
<nav>
<router-link to="/">Главная</router-link> |
<router-link to="/about">О проекте</router-link>
</nav>
<router-view />
</template>
Итоговое задание
Мини-приложение с <script setup>
:
- На главной странице — компонент со счётчиком из Pinia.
- Компонент принимает
props
и возвращает сообщение черезemit
. - Две страницы: «Главная» и «О проекте» (Vue Router).